package com.zp.mvppractice.io;

import android.content.Context;

import com.zp.mvppractice.App;
import com.zp.mvppractice.BuildConfig;
import com.zp.mvppractice.utils.FileUtils;
import com.zp.mvppractice.utils.PhoneStateUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by izp on 2017/4/14.
 */

public class NetHelper {
    private static NetHelper sInstance;
    private OkHttpClient mOkHttpClient = null;
    private final String NETWORK_CACHE_DIR = "NetCache";
    private Apis.PaymentButler mPaymentButler;
    private NetHelper(){
    }

    public static NetHelper getInstance(){
        return InstanceHolder.sNetHelper;
    }
    private static class InstanceHolder {
        static NetHelper sNetHelper = new NetHelper();
    }

    private OkHttpClient getClient(final Context context, final boolean cacheEnable){
        if (null==mOkHttpClient){
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            File cacheFile = new File(FileUtils.getNetCacheDir(App.getAppContext(),NETWORK_CACHE_DIR));//把路径名称转换为文件对象
            Cache cache = new Cache(cacheFile,1024*1024*50);//50m
            Interceptor cacheInterceptor = new Interceptor() {//cacheInterceptor是需要服务器支持的，但是没想通为什么
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    long t1 = System.nanoTime();//请求发起的时间
                    long date1 = System.currentTimeMillis();//发起请求的时间点
                    if (BuildConfig.IS_DEBUG){
//                        LogMe.v(StringUtils.getRequestString(request,t1,date1));
                    }
                    //检查网络状态需要权限ACCESS_NETWORK_STATE
                    if (cacheEnable && !PhoneStateUtils.isNetworkConnected(context)){//网络不可用
                        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();//则强制启用缓存
                    }
                    Response response = chain.proceed(request);//这里的response就有可能是从缓存中获取到的
                    if (BuildConfig.IS_DEBUG){
//                        LogMe.v(StringUtils.getResponseString(response,t1,date1));
                    }
                    if (cacheEnable){
                        if (PhoneStateUtils.isNetworkConnected(context)){//如果网络连接正常
                            int maxAge = 0;
                            // 有网络时, 不缓存, 最大保存时长为0
                            response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge)
                                    .removeHeader("Pragma")
                                    .build();
                        }else {
                            // 无网络时，设置超时为4周
                            int maxStale = 60 * 60 * 24 * 28;
                            response.newBuilder()
                                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                                    .removeHeader("Pragma")
                                    .build();
                        }
                    }
                    return response;
                }
            };
            //设置缓存
//            builder.addNetworkInterceptor(cacheInterceptor);
            builder.addInterceptor(cacheInterceptor);//我有一次添加了NetworkInterceptor之后，网络请求就不好用了，
            builder.cache(cache);
            //设置超时
            builder.connectTimeout(10, TimeUnit.SECONDS);
            builder.readTimeout(20, TimeUnit.SECONDS);
            builder.writeTimeout(20, TimeUnit.SECONDS);
            //错误重连
            builder.retryOnConnectionFailure(true);
            mOkHttpClient = builder.build();
        }
        return mOkHttpClient;
    }

    /**
     * 添加头部
     *
     * @param request 请求对象
     * @return
     */
    private Request addHeaders(Request request) {
        Request.Builder builder = request.newBuilder();

        builder.addHeader("Connection", "Keep-Alive")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Accept-Language", "zh-CN,en-US");
        return builder.build();
    }

    private  <T> T getApiService(String baseUrl, Class<T> clz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(getClient(App.getAppContext(),false))
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return retrofit.create(clz);
    }

//    public Apis.Splash getSplash(){
//        return getApiService(BuildConfig.IS_DEBUG ?TESTURL:BASEURL, Apis.Splash.class);
//    }

    Apis.PaymentButler getPaymentButler(){
        if (mPaymentButler == null) {
            mPaymentButler = NetHelper.getInstance().getApiService(Apis.PaymentButler.baseUrl,Apis.PaymentButler.class);
        }
        return mPaymentButler;
    }
}
